package com.changgou.web.filter;

import com.changgou.web.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author wz
 * @company 公司
 * @create 2020-03-30 10:24
 */
@Component
public class Authorize implements GlobalFilter, Ordered {
    @Autowired
    private AuthService authService;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取当前请求对象
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        //判断当前请求路径是否为登录请求,如果是直接放行
        String path = request.getURI().getPath();
        if ("/api/oauth/login".equals(path) || !UrlFilter.hasAuthorize(path)){
            //放行
           return chain.filter(exchange);
        }
        //从cookie中获取jti的值,如果该值不存在, 拒绝本次访问
       String jti =  authService.getJtiFromCookie(request);
        if (StringUtils.isEmpty(jti)){
            //拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //cookie中有值就行redis中取值,如果该值不存在拒绝本次访问
       String jwt= authService.getJwtFromRedis(jti);
        //有可能不存在
        if (StringUtils.isEmpty(jwt)){
            //决绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //redis中jwt存在,对请求增强进行携带令牌信息
        request.mutate().header("Authorization","Bearer "+jwt);
        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
